import {createStore} from "vuex";
import {menuList} from "../api/menu";
import {listByIds} from "../api/route";
import routes from "../router";
import {userInfo} from "../api/account";
import Socket from "../utils/Socket";

function getRouteIds(rows, ids = []) {
    rows.forEach(item => {
        ids.push(item.routeId);
        getRouteIds(item.children, ids);
    })
}

export default createStore({
    state: {
        toggle: true,
        dictionary: [],
        menus: [],
        routeIds: [],
        userInfo: {},
        socket: {}
    },
    actions: {

        /**
         * 获取菜单
         * @param context
         * @param payload
         * @returns {Promise<any>}
         */
        getMenus(context, payload){
            return new Promise((resolve, reject) => {
                menuList().then(res => {
                    context.commit('setMenus', res.data);
                    const ids = []
                    getRouteIds(res.data, ids);
                    context.commit('setRouteIds', ids);
                    return resolve(res.data);
                }).catch(()=>{
                    return reject()
                });

            })
        },

        /**
         * 设置动态路由
         * @param context
         * @param payload
         * @returns {Promise<any>}
         */
        setRouter(context, payload){
            return new Promise((resolve, reject) => {
                listByIds(this.state.routeIds.filter(e => e).join(",")).then(res => {
                    res.data.forEach(item => {
                        const data =  {
                            path: `/${item.path}`,
                            component: ()=> import(`@/page/${item.component}/index.vue`),
                            children: item.children.map(child => {
                                return {
                                    path: `/${child.path}`,
                                    component: () => import(`@/page/${child.component}/index.vue`),
                                }
                            })
                        };
                        routes.addRoute(data);
                    });
                    return resolve();
                }).catch(()=>{
                    return reject();
                })
            })
        },

        /**
         * 获取用户信息
         * @param context
         * @param payload
         */
        getUserInfo(context, payload){
            return new Promise((resolve, reject) => {
                userInfo().then(res => {
                    context.commit('setUserInfo',  res.data);
                    return resolve(res.data);
                }).catch((e)=>{
                    console.error(e);
                    return reject(e);
                });
            })
        },

        /**
         * 获取连接的
         * @param {*} context 
         * @param {*} plyload 
         */
        socketConnection(context, plyload){
            const userId = localStorage.getItem("userId");
            if(userId){
                const socket = new Socket(userId, '1');
                context.commit('setSocket', socket);
            }
        }
    },
    getters: {
    },
    mutations: {
        setToggle: (state, toggle) => {
            state.toggle = toggle;
        },
        setDictionary: (state, dictionary) => {
            state.dictionary = dictionary;
        },
        setMenus: (state, menus) => {
            state.menus = menus;
        },
        setRouteIds: (state, routeIds) => {
            state.routeIds = routeIds;
        },
        setUserInfo: (state, userInfo) => {
            state.userInfo = userInfo;
        },
        setSocket: (state, socket) => {
            state.socket = socket;
        }
    }
})
